﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Drawing;
using System.Reflection;
using MediaArtAggregator.Core.SearchProvider;
using System.Xml.Linq;

namespace MediaArtAggregator.Core {
  public static class Utilities {
    public static string GetSafeSearchString ( string s ) {
      return HttpUtility.UrlEncode ( s );
    }

    static Utilities ( ) {
    }

    public static bool HasArtFile ( DirectoryInfo dir, string imageName ) {
      return dir.GetFiles ( imageName + ".jpg" ).Length == 1;
    }

    public static Color GetColorFromString ( string color ) {
      return ColorTranslator.FromHtml ( string.IsNullOrEmpty ( color ) ? "lightblue" : color );
    }

    public static Image CreateImageWithSizeInfo ( Image orig, Size newSize ) {
      Image nImg = new Bitmap ( orig, newSize );
      Font fnt = new Font ( "Arial", 10, FontStyle.Bold, GraphicsUnit.Point );
      Graphics g = Graphics.FromImage ( nImg );
      string size = string.Format ( "{0}x{1}", orig.Height, orig.Width );
      SizeF stringSize = g.MeasureString ( size, fnt );
      Rectangle rect = new Rectangle ( nImg.Width - ( int ) stringSize.Width - 2, nImg.Height - ( int ) stringSize.Height - 2, ( int ) stringSize.Width + 4, ( int ) stringSize.Height + 4 );
      g.FillRectangle ( new SolidBrush ( Color.Black ), rect );
      StringFormat sf = new StringFormat ( StringFormatFlags.NoWrap );
      sf.Alignment = sf.LineAlignment = StringAlignment.Center;
      g.DrawString ( size, fnt, new SolidBrush ( Color.White ), rect, sf );
      return nImg;
    }

    public static Type[ ] GetSourceProviderTypes ( ) {
      List<Type> resultTypes = new List<Type> ( );
      string startPath = Path.GetDirectoryName(typeof(Utilities).Assembly.Location);
      XDocument provDoc = XDocument.Load ( Path.Combine ( startPath, "providers.xml" ) );

      var providers = from p in provDoc.Root.Elements ( "provider" )
                      select p.Attribute ( "assembly" ).Value;

      foreach ( string asmName in providers ) {
        try {
          Assembly asm = Assembly.Load ( asmName );
          List<Type> coreTypes = Utilities.GetProviderTypesForAssembly ( asm );
          if ( coreTypes != null )
            resultTypes.AddRange ( coreTypes );
        } catch { }
      }

      return resultTypes.ToArray<Type> ( );
    }

    private static List<Type> GetProviderTypesForAssembly ( Assembly asm ) {
      if ( asm == null )
        return null;
      List<Type> resultTypes = new List<Type> ( );
      Type[ ] allTypes = asm.GetTypes ( );
      foreach ( Type t in allTypes ) {
        if ( !t.IsAbstract && t.IsClass && t.IsSubclassOf ( typeof ( SearchSource ) ) ) {
          resultTypes.Add ( t );
        }
      }
      return resultTypes;
    }
  }
}
